<?php

class CouponsController extends AppController {

  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session', 'Util', 'Upload');
  public $name = 'Coupons';
  public $paginate;

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'Coupon.start_date' => 'desc', 'Coupon.end_date' => 'desc'
            ));
  }

  //reference: http://stackoverflow.com/questions/5355911/cakephp-1-3-query-question
  //http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
  function company_service($serviceId=null){

    if(empty($serviceId)){
      throw new NotFoundException();
    } else {
      //http://stackoverflow.com/questions/5728932/cakephp-this-paginate-with-custom-join-and-filtering-options --doc
      $this->loadModel('Service');
      $serviceInfo = $this->Service->find('first',array('conditions'=>array('Service.id'=>$serviceId), 'fields'=>array('Service.id', 'Service.name', 'Service.description')));
      if(empty($serviceInfo)) {
        throw new NotFoundException();
      }
      $this->paginate = array(
            'fields'=>array('Company.name','Company.description','Company.id as company_id','Company.image_path','Ad.id as ad_id','Ad.description as ad_description','Ad.start_date','Ad.end_date'),
          'conditions'=>array('Company.service_id'=>$serviceId,'Ad.start_date <= Now()','Ad.end_date >= Now()'),
          'order'=>array('Company.name'=>'asc'),
          'recursive'=>1,
          'limit' => Configure::read('App.pageResultLimit')
      );
      $companies = $this->paginate($this->Company->Ad);
      $this->set('title_for_layout','Isle Vow '.$serviceInfo['Service']['name']);
      $this->set('companies', $companies);
      $this->set('serviceInfo', $serviceInfo);
      //--Debug the output of a query
      //$db =ConnectionManager::getDataSource('default');
     //debug($db->showLog());
    }
  }

  function view($couponId){

    if(empty($couponId)){
      throw new NotFoundException();
    } else {
      $opts = array(
            'fields'=>array('Coupon.id as coupon_id','Coupon.title', 'Coupon.description', 'Coupon.url', 'Coupon.start_date', 'Coupon.end_date','Coupon.valid_start_date', 'Coupon.valid_end_date', 'Coupon.image_path', 'Company.id as company_id','Company.name','Company.image_path', 'Company.address', 'Company.phone' ,'Company.phone_additional',  'Company.fax', 'Company.email', 'Company.url', 'Company.facebook_url','Company.twitter_url','Company.pinterest_url'),
            'conditions'=>array('Coupon.id'=>$couponId,'Coupon.start_date <= Now()','Coupon.end_date >= Now()')
      );
      $coupon = $this->Coupon->find('all',$opts);
      if(!empty($coupon)){
        $this->layout='coupon';
        $coupon = $coupon[0];
        $this->set("title_for_layout","Isle Vow - Coupon for ". $coupon['Company']['name']);
        $this->set("meta_keywords","Isle Vow Coupon ". $coupon['Company']['name']); //TODO
        $this->set("meta_description","Coupon for products and services being offered by ". $coupon['Company']['name'] .' at Isle Vow');
        $this->set(array('couponInfo'=> $coupon));

      } else {
        throw new NotFoundException("This is not a valid coupon or the coupon is no longer available!");
      }
    }
  }

  //admin
  function admin_index() {
    $this->layout = "admin";
    $this->set('coupons', $this->paginate('Coupon'));
  }

  function admin_add() {
    $this->layout = "admin";
    $this->loadModel('Company');
    $this->set('options', $this->Company->find('list', array('fields'=> array('Company.id','Company.name'), 'order'=>array('name'=>'asc')  )));
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    }
  }

  //admin
  function admin_edit($id = null) {
    $this->layout = "admin";
    $this->loadModel('Company');
    $this->set('options', $this->Company->find('list', array('fields'=> array('Company.id','Company.name'), 'order'=>array('name'=>'asc')  )));
    $this->Coupon->id = $id;
    if ($this->request->is('get')) {
      $this->request->data = $this->Coupon->read();
      $this->request->data['Coupon']['start_date'] = $this->Util->formatDate($this->request->data['Coupon']['start_date'], true);
      $this->request->data['Coupon']['end_date'] = $this->Util->formatDate($this->request->data['Coupon']['end_date'], true);
      $this->request->data['Coupon']['valid_start_date'] = $this->Util->formatDate($this->request->data['Coupon']['valid_start_date'], true);
      $this->request->data['Coupon']['valid_end_date'] = $this->Util->formatDate($this->request->data['Coupon']['valid_end_date'], true);
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

  private function _processAction($dataIn, $action='add', $id=null) {
    $data = $this->_processRequestData($dataIn);
    $this->Coupon->set($data);
    if ($this->Coupon->validates()) {
        $data["Coupon"]["start_date"] = $this->Util->formatDate($data["Coupon"]["start_date"]);
        $data["Coupon"]["end_date"] = $this->Util->formatDate($data["Coupon"]["end_date"]);
        $data["Coupon"]["valid_start_date"] = $this->Util->formatDate($data["Coupon"]["valid_start_date"]);
        $data["Coupon"]["valid_end_date"] = $this->Util->formatDate($data["Coupon"]["valid_end_date"]);
      if (!empty($data["Coupon"]["image_path"]) && !empty($data["Coupon"]["image_path"]['name'])) {
        $imageUploaded = $this->Upload->uploadImage($data["Coupon"]["image_path"], WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . Configure::read('App.couponsImageFolder'), Configure::read('App.couponsImageWidth'));
        $data["Coupon"]["image_path"] = Configure::read('App.couponsImageFolder') . '/' . $imageUploaded;
      } else {
        if ($action === 'add') {
          $data["Coupon"]["image_path"] = null;
        } else {
          $data["Coupon"]["image_path"] = isset($data["Coupon"]["_image_path"]) ? $data["Coupon"]["_image_path"] : null;
        }
      }
      if ($this->Coupon->save($data, false)) {
        $this->Session->setFlash('The record was successfully saved.');
        $this->redirect(array('action' => 'index'));
      }
    } else {
      if ($action !== 'add') {
        //getting previous image
        $data['Coupon']['image_path'] = $data["Coupon"]["_image_path"];
        $data['Coupon']['id'] = $id;
      }
      $this->request->data['Coupon'] = $data['Coupon'];
      $this->set('errors', $this->Coupon->validationErrors);
    }
    if ($action === 'add') {
      $this->render('admin_add');
    } else {
      $this->render('admin_edit');
    }
  }

  //admin
  function admin_delete($id) {
    $this->layout = "admin";
    $this->admin_deleteImage($id, false);
    if ($this->Coupon->delete($id)) {
      $this->Session->setFlash('The record has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
  }

  //admin
  function admin_deleteImage($id, $redirect=true) {
    $this->layout = "admin";
    $image = $this->Coupon->read('image_path', $id);
    $imagePath = $image['Coupon']['image_path'];
    if (!empty($imagePath)) {
      $result = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
      $this->Coupon->save(array('Coupon' => array('id' => $id, 'image_path' => '')), false, array('image_path'));
      if ($redirect) {
        $this->Session->setFlash('The image has been deleted.');
        $this->redirect(array('action' => 'edit', $id));
      }
    }
  }

}

?>
